/**
 * BossManager - Boss管理器
 * 负责Boss的生成、管理和Boss战逻辑的控制
 */

import { Boss, BossType, BossState, type BossOptions } from './Boss'
import type { Player } from './Player'
import type { EntityManager } from './EntityManager'
import type { GameEngine } from './GameEngine'

export interface BossEncounter {
  bossType: BossType
  triggerDistance: number    // 触发距离
  spawnX: number            // 生成X坐标
  spawnY: number            // 生成Y坐标
  isTriggered: boolean      // 是否已触发
  isCompleted: boolean      // 是否已完成
  rewards: BossReward[]     // 奖励列表
}

export interface BossReward {
  type: 'score' | 'coins' | 'health' | 'powerup'
  amount: number
  description: string
}

export interface BossManagerOptions {
  gameEngine: GameEngine
  entityManager: EntityManager
  encounters?: BossEncounter[]
  bossSpawnDistance?: number  // Boss生成的基础距离间隔
}

export class BossManager {
  private gameEngine: GameEngine
  private entityManager: EntityManager
  private encounters: BossEncounter[]
  private currentBoss: Boss | null = null
  private bossSpawnDistance: number
  private lastBossDistance: number = 0
  
  // Boss战状态
  private isBossFight: boolean = false
  private bossFightStartTime: number = 0
  private bossFightMusic: string | null = null
  
  // 事件回调
  private onBossSpawnCallback?: (boss: Boss) => void
  private onBossDefeatedCallback?: (boss: Boss, rewards: BossReward[]) => void
  private onBossFightStartCallback?: () => void
  private onBossFightEndCallback?: () => void
  
  constructor(options: BossManagerOptions) {
    this.gameEngine = options.gameEngine
    this.entityManager = options.entityManager
    this.bossSpawnDistance = options.bossSpawnDistance || 1000 // 每1000距离单位生成一个Boss
    
    // 初始化Boss遭遇配置
    this.encounters = options.encounters || this.createDefaultEncounters()
  }
  
  /**
   * 更新Boss管理器
   */
  update(deltaTime: number, player: Player): void {
    // 检查是否需要生成新Boss
    this.checkBossSpawn(player)
    
    // 更新当前Boss战状态
    this.updateBossFight(deltaTime, player)
    
    // 检查Boss是否被击败
    this.checkBossDefeat(player)
  }
  
  /**
   * 检查Boss生成条件
   */
  private checkBossSpawn(player: Player): void {
    if (this.isBossFight || this.currentBoss) {
      return // 已经在Boss战中或已有Boss存在
    }
    
    const playerDistance = player.stats.distance
    
    // 检查是否达到Boss生成距离
    if (playerDistance - this.lastBossDistance >= this.bossSpawnDistance) {
      this.spawnNextBoss(player)
    }
    
    // 检查特定距离触发的Boss遭遇
    for (const encounter of this.encounters) {
      if (!encounter.isTriggered && playerDistance >= encounter.triggerDistance) {
        this.triggerBossEncounter(encounter, player)
        break
      }
    }
  }
  
  /**
   * 生成下一个Boss
   */
  private spawnNextBoss(player: Player): void {
    // 根据玩家进度选择Boss类型
    const bossType = this.selectBossType(player.stats.distance)
    
    // 计算Boss生成位置
    const spawnX = player.x + 400 // 在玩家前方400像素生成
    const spawnY = 200 // 固定高度
    
    // 创建Boss
    const boss = this.createBoss(bossType, spawnX, spawnY, player.stats.distance)
    
    this.spawnBoss(boss, player)
    this.lastBossDistance = player.stats.distance
  }
  
  /**
   * 触发特定Boss遭遇
   */
  private triggerBossEncounter(encounter: BossEncounter, player: Player): void {
    encounter.isTriggered = true
    
    // 创建Boss
    const boss = this.createBoss(encounter.bossType, encounter.spawnX, encounter.spawnY, player.stats.distance)
    
    this.spawnBoss(boss, player)
    
  }
  
  /**
   * 生成Boss
   */
  private spawnBoss(boss: Boss, player: Player): void {
    this.currentBoss = boss
    this.entityManager.addEntity(boss)
    
    // 设置Boss目标为玩家
    boss.setTarget(player)
    
    // 开始Boss战
    this.startBossFight()
    
    // 触发回调
    if (this.onBossSpawnCallback) {
      this.onBossSpawnCallback(boss)
    }
    
    console.log(`生成Boss: ${boss.bossType}, 生命值: ${boss.health}`)
  }
  
  /**
   * 开始Boss战
   */
  private startBossFight(): void {
    this.isBossFight = true
    this.bossFightStartTime = Date.now()
    
    // 改变游戏状态（可以暂停背景滚动、改变音乐等）
    this.gameEngine.setBossFightMode(true)
    
    // 触发回调
    if (this.onBossFightStartCallback) {
      this.onBossFightStartCallback()
    }
    
    console.log('Boss战开始!')
  }
  
  /**
   * 结束Boss战
   */
  private endBossFight(): void {
    this.isBossFight = false
    this.bossFightStartTime = 0
    
    // 恢复正常游戏状态
    this.gameEngine.setBossFightMode(false)
    
    // 触发回调
    if (this.onBossFightEndCallback) {
      this.onBossFightEndCallback()
    }
    
    console.log('Boss战结束!')
  }
  
  /**
   * 更新Boss战状态
   */
  private updateBossFight(deltaTime: number, player: Player): void {
    if (!this.isBossFight || !this.currentBoss) {
      return
    }
    
    // 检查Boss是否还在活动范围内
    const distanceToBoss = Math.abs(this.currentBoss.x - player.x)
    if (distanceToBoss > 800) { // 如果Boss距离玩家太远
      this.currentBoss.clearTarget()
    } else {
      this.currentBoss.setTarget(player)
    }
    
    // 检查Boss弹幕与玩家的碰撞
    this.checkProjectileCollisions(player)
  }
  
  /**
   * 检查弹幕碰撞
   */
  private checkProjectileCollisions(player: Player): void {
    if (!this.currentBoss) return
    
    const projectiles = this.currentBoss.getProjectiles()
    
    for (const projectile of projectiles) {
      if (this.checkCollision(player, projectile)) {
        // 玩家受到伤害
        player.takeDamage(projectile.damage)
        
        // 销毁弹幕
        projectile.destroy()
        
        console.log(`玩家被Boss弹幕击中，受到${projectile.damage}点伤害`)
      }
    }
  }
  
  /**
   * 检查Boss是否被击败
   */
  private checkBossDefeat(player: Player): void {
    if (!this.currentBoss || this.currentBoss.state !== BossState.DEFEATED) {
      return
    }
    
    // Boss被击败，给予奖励
    const rewards = this.calculateRewards(this.currentBoss, player)
    this.giveRewards(player, rewards)
    
    // 标记遭遇完成
    this.markEncounterCompleted(this.currentBoss)
    
    // 触发回调
    if (this.onBossDefeatedCallback) {
      this.onBossDefeatedCallback(this.currentBoss, rewards)
    }
    
    console.log(`Boss ${this.currentBoss.bossType} 被击败!`)
    
    // 清理Boss
    this.entityManager.removeEntityByReference(this.currentBoss)
    this.currentBoss = null
    
    // 结束Boss战
    this.endBossFight()
  }
  
  /**
   * 计算奖励
   */
  private calculateRewards(boss: Boss, player: Player): BossReward[] {
    const baseScore = 1000
    const baseCoins = 50
    
    // 根据Boss类型和玩家表现计算奖励
    const multiplier = this.getBossRewardMultiplier(boss.bossType)
    const timeBonus = this.calculateTimeBonus()
    
    return [
      {
        type: 'score',
        amount: Math.floor(baseScore * multiplier * timeBonus),
        description: `击败${boss.bossType}获得分数奖励`
      },
      {
        type: 'coins',
        amount: Math.floor(baseCoins * multiplier),
        description: `击败${boss.bossType}获得金币奖励`
      },
      {
        type: 'health',
        amount: 1,
        description: '击败Boss恢复生命值'
      }
    ]
  }
  
  /**
   * 给予奖励
   */
  private giveRewards(player: Player, rewards: BossReward[]): void {
    for (const reward of rewards) {
      switch (reward.type) {
        case 'score':
          player.stats.score += reward.amount
          break
        case 'coins':
          player.stats.coinsCollected += reward.amount
          break
        case 'health':
          player.heal(reward.amount)
          break
        case 'powerup':
          // 这里可以给玩家特殊道具
          break
      }
      
      console.log(`奖励: ${reward.description} (+${reward.amount})`)
    }
  }
  
  /**
   * 标记遭遇完成
   */
  private markEncounterCompleted(boss: Boss): void {
    for (const encounter of this.encounters) {
      if (encounter.bossType === boss.bossType && encounter.isTriggered && !encounter.isCompleted) {
        encounter.isCompleted = true
        break
      }
    }
  }
  
  /**
   * 根据距离选择Boss类型
   */
  private selectBossType(distance: number): BossType {
    if (distance < 2000) {
      return BossType.GUARDIAN
    } else if (distance < 5000) {
      return Math.random() < 0.5 ? BossType.GUARDIAN : BossType.DESTROYER
    } else {
      const rand = Math.random()
      if (rand < 0.33) return BossType.GUARDIAN
      if (rand < 0.66) return BossType.DESTROYER
      return BossType.PHANTOM
    }
  }
  
  /**
   * 创建Boss
   */
  private createBoss(bossType: BossType, x: number, y: number, playerDistance: number): Boss {
    // 根据玩家进度调整Boss属性
    const difficultyMultiplier = 1 + Math.floor(playerDistance / 1000) * 0.2
    
    const options: BossOptions = {
      x,
      y,
      width: 80,
      height: 80,
      bossType,
      maxHealth: Math.floor(this.getBaseBossHealth(bossType) * difficultyMultiplier),
      moveSpeed: this.getBaseBossSpeed(bossType),
      detectionRange: 350
    }
    
    return new Boss(options)
  }
  
  /**
   * 获取Boss基础生命值
   */
  private getBaseBossHealth(bossType: BossType): number {
    switch (bossType) {
      case BossType.GUARDIAN:
        return 100
      case BossType.DESTROYER:
        return 150
      case BossType.PHANTOM:
        return 80
      default:
        return 100
    }
  }
  
  /**
   * 获取Boss基础速度
   */
  private getBaseBossSpeed(bossType: BossType): number {
    switch (bossType) {
      case BossType.GUARDIAN:
        return 50
      case BossType.DESTROYER:
        return 30
      case BossType.PHANTOM:
        return 80
      default:
        return 50
    }
  }
  
  /**
   * 获取Boss奖励倍数
   */
  private getBossRewardMultiplier(bossType: BossType): number {
    switch (bossType) {
      case BossType.GUARDIAN:
        return 1.0
      case BossType.DESTROYER:
        return 1.5
      case BossType.PHANTOM:
        return 1.2
      default:
        return 1.0
    }
  }
  
  /**
   * 计算时间奖励倍数
   */
  private calculateTimeBonus(): number {
    if (!this.isBossFight) return 1.0
    
    const fightDuration = Date.now() - this.bossFightStartTime
    const maxBonusTime = 30000 // 30秒内击败有时间奖励
    
    if (fightDuration <= maxBonusTime) {
      return 1.0 + (maxBonusTime - fightDuration) / maxBonusTime * 0.5 // 最多50%时间奖励
    }
    
    return 1.0
  }
  
  /**
   * 简单的碰撞检测
   */
  private checkCollision(entity1: { x: number; y: number; width: number; height: number }, 
                        entity2: { x: number; y: number; width: number; height: number }): boolean {
    return (
      entity1.x < entity2.x + entity2.width &&
      entity1.x + entity1.width > entity2.x &&
      entity1.y < entity2.y + entity2.height &&
      entity1.y + entity1.height > entity2.y
    )
  }
  
  /**
   * 创建默认Boss遭遇配置
   */
  private createDefaultEncounters(): BossEncounter[] {
    return [
      {
        bossType: BossType.GUARDIAN,
        triggerDistance: 1000,
        spawnX: 600,
        spawnY: 200,
        isTriggered: false,
        isCompleted: false,
        rewards: [
          { type: 'score', amount: 1500, description: '首次Boss战胜利奖励' },
          { type: 'coins', amount: 100, description: '首次Boss战金币奖励' }
        ]
      },
      {
        bossType: BossType.DESTROYER,
        triggerDistance: 3000,
        spawnX: 600,
        spawnY: 200,
        isTriggered: false,
        isCompleted: false,
        rewards: [
          { type: 'score', amount: 2500, description: '毁灭者Boss战胜利奖励' },
          { type: 'coins', amount: 150, description: '毁灭者Boss战金币奖励' }
        ]
      },
      {
        bossType: BossType.PHANTOM,
        triggerDistance: 5000,
        spawnX: 600,
        spawnY: 200,
        isTriggered: false,
        isCompleted: false,
        rewards: [
          { type: 'score', amount: 3000, description: '幻影Boss战胜利奖励' },
          { type: 'coins', amount: 200, description: '幻影Boss战金币奖励' }
        ]
      }
    ]
  }
  
  /**
   * 设置事件回调
   */
  setOnBossSpawn(callback: (boss: Boss) => void): void {
    this.onBossSpawnCallback = callback
  }
  
  setOnBossDefeated(callback: (boss: Boss, rewards: BossReward[]) => void): void {
    this.onBossDefeatedCallback = callback
  }
  
  setOnBossFightStart(callback: () => void): void {
    this.onBossFightStartCallback = callback
  }
  
  setOnBossFightEnd(callback: () => void): void {
    this.onBossFightEndCallback = callback
  }
  
  /**
   * 获取当前Boss
   */
  getCurrentBoss(): Boss | null {
    return this.currentBoss
  }
  
  /**
   * 检查是否在Boss战中
   */
  isBossFightActive(): boolean {
    return this.isBossFight
  }
  
  /**
   * 获取Boss遭遇列表
   */
  getEncounters(): BossEncounter[] {
    return [...this.encounters]
  }
  
  /**
   * 添加自定义Boss遭遇
   */
  addEncounter(encounter: BossEncounter): void {
    this.encounters.push(encounter)
  }
  
  /**
   * 强制生成Boss（用于测试）
   */
  forceBossSpawn(bossType: BossType, player: Player): Boss {
    const boss = this.createBoss(bossType, player.x + 300, 200, player.stats.distance)
    this.spawnBoss(boss, player)
    return boss
  }
  
  /**
   * 清理所有Boss
   */
  cleanup(): void {
    if (this.currentBoss) {
      this.entityManager.removeEntityByReference(this.currentBoss)
      this.currentBoss = null
    }
    
    if (this.isBossFight) {
      this.endBossFight()
    }
    
    // 重置所有遭遇状态
    this.encounters.forEach(encounter => {
      encounter.isTriggered = false
      encounter.isCompleted = false
    })
    
    this.lastBossDistance = 0
  }
  
  /**
   * 获取管理器状态信息
   */
  getStatus(): {
    isBossFight: boolean
    currentBoss: string | null
    completedEncounters: number
    totalEncounters: number
    lastBossDistance: number
  } {
    return {
      isBossFight: this.isBossFight,
      currentBoss: this.currentBoss?.bossType || null,
      completedEncounters: this.encounters.filter(e => e.isCompleted).length,
      totalEncounters: this.encounters.length,
      lastBossDistance: this.lastBossDistance
    }
  }
}